<template>
	<comRoot>
		<template #page>
			<image v-if="commonConfigs && commonConfigs.domainFrontFileLink" :src="`${commonConfigs.domainFrontFileLink}/files/images/page-bg.png`" class="bg" />
			
			<comDetailNavigateBack title="我的设置" />

			<view class="setting-box relative">
				<scroll-view
					scroll-y
					:style="{
						height: 'calc(100vh - ' + commonNavHeight + ' - 28rpx)'
					}"
				>
					<view class="setting-form-view relative">
						<label class="form-item-view relative flex-align-items-center">
							<view class="item-view-title"> 头像 </view>
							<view class="item-view-avatar flex-all-center">
								<image style="border-radius: 100%;width: 80rpx;height: 80rpx;" class="block" :src="form.avatar || '/static/apps/login/avatar.png'" mode=""></image>
							</view>
						</label>

						<label class="form-item-view relative flex-align-items-center">
							<view class="item-view-title"> 昵称 </view>
							<input
								:style="{
									color: userInfo.nickname ? '#FFDA4D' : '#FFDA4D'
								}"
								class="truncate"
								type="text"
								disabled
								v-model="form.nickname"
								placeholder="请输入"
								placeholder-style="color:#ccc"
								value=""
							/>
						</label>

						<label class="form-item-view relative flex-align-items-center" @click="copyTxtData(userInfo.id || form.id || '')">
							<view class="item-view-title"> UID </view>
							<input
								:style="{
									flex: 1,
									color: userInfo.id ? '#FFDA4D' : '#ccc'
								}"
								type="text"
								v-model="form.id"
								placeholder="请输入"
								placeholder-style="color:#ccc"
								value=""
								disabled
							/>
							
							<image
							class="absolute" src="/static/images/user_imgs/copy-icon.png" mode="" 
							style="width: 26rpx; height: 26rpx; right: 20rpx;z-index: 100;"
							></image>
						</label>

						<label class="form-item-view relative flex-align-items-center" @click="copyTxtData(userInfo.openid || form.openid || '')">
							<view class="item-view-title"> OpenID </view>
							<view
								:style="{
									flex: 1,
									color: userInfo.openid ? '#FFDA4D' : '#ccc'
								}"
								class="truncate"
							>
								{{ form.openid }}
							</view>
							
							<image 
							class="absolute" src="/static/images/user_imgs/copy-icon.png" mode="" 
							style="width: 26rpx; height: 26rpx; right: 20rpx;z-index: 100;"
							></image>
						</label>

						<label class="form-item-view relative flex-align-items-center">
							<view class="item-view-title"> 手机号码 </view>
							<input
								type="number"
								:style="{
									color: userInfo.phone ? '#FFDA4D' : '#FFDA4D'
								}"
								:disabled="userInfo.phone ? true : false"
								:maxlength="11"
								v-model="form.phone"
								placeholder="请绑定手机号码"
								placeholder-style="color:#ccc"
								value=""
							/>
						</label>

						<label class="form-item-view relative flex-align-items-center" v-if="!userInfo.phone">
							<view class="item-view-title"> 验证码 </view>

							<input type="number" :maxlength="6" v-model="form.code" placeholder="请输入" placeholder-style="color:#ccc" value="" />

							<button
								:disabled="isAllowOper"
								@click="getCodeFun"
								type="primary"
								:class="
									isAllowOper ? 'flex items-center justify-content-center' : 'flex items-center justify-content-center'
								"
								>{{ msg }}</button
							>
						</label>
					</view>

					<view class="tip-txt" v-if="!userInfo.phone">
						<view> <text class="tip-txt-left">*</text> 手机号仅可绑定一次！</view>
						<view> <text class="tip-txt-left">*</text> 如有小程序账号，请关联小程序所绑定的手机号。</view>
					</view>

					<view class="beian-content flex flex-direction-column">
						<view>ICP备案号:粤ICP备2024167794号-7A</view>
						<view class="flex flex-wrap">
							<view style="white-space: nowrap;">Copyright@2024-2025 旺卡抽赏 All Rights Reserved.</view>
							<view style="margin-left: 6rpx; white-space: nowrap;"> v{{ appVersion || '1.0.0' }}-{{ commonConfigs.appPackageVer }} </view>
						</view>
					</view>

					<view class="save-btns relative flex-all-center" @click="setSaveFun" v-if="!userInfo.phone"> 
						<image v-if="commonConfigs && commonConfigs.domainFrontFileLink" :src="`${commonConfigs.domainFrontFileLink}/files/images/user/settings-sumbit-bg.png`" class="bg" />
						<view class="relative">保存设置</view>
					 </view>

					<view class="save-btns relative flex-all-center" style="margin-top: 20rpx" @click="loginDelFun" v-if="isShowIOSDelUser"> 
						<image v-if="commonConfigs && commonConfigs.domainFrontFileLink" :src="`${commonConfigs.domainFrontFileLink}/files/images/user/settings-sumbit-bg.png`" class="bg" />
						<view class="relative">注销账户</view>
					</view>

					<view
						:class="['logout-box', 'flex-all-center', 'relative', userInfo.phone ? 'logout-box-active' : '']"
						@click="loginOutFun"
					>
						<image v-if="commonConfigs && commonConfigs.domainFrontFileLink" :src="`${commonConfigs.domainFrontFileLink}/files/images/user/settings-sumbit-bg.png`" class="bg" />
						<view class="relative">退出登录</view>
					</view>
				</scroll-view>
			</view>
		</template>
	</comRoot>
</template>

<script>
	import {
		getUserCodeApi,
		getUpdatePhoneApi,
		getUpdateUserInfoApi,
		getUserDestroyApi
	} from '@/setupproject/INTERFACE';

	import { setAsyncFunWait, getMobileIsFun } from '@/setupproject/TOOLS_FUN';

	import store from '@/store';

	import { ACTIONS } from '@/store/modules/userStore';

	import { base64ToPath, pathToBase64 } from 'image-tools';

	export default {
		data() {
			return {
				uniAPPID: '',
				appVersion: '',
				isShowIOSDelUser: false,
				form: {
					id: '',
					code: '',
					avatar: '',
					phone: '',
					openid: '',
					nickname: '',
				},
				msg: '获取验证码',
				time: 60,
				timer: null,
				isAllowOper: false,
			};
		},
		computed: {
			commonOnline() {
				return this.$store.getters.commonOnline;
			},
			commonConfigs() {
				return this.$store.getters.commonConfigs || {};
			},
			commonNavHeight() {
				return this.$store.getters.commonNavHeight + 'px';
			},
			userInfo() {
				return this.$store.getters.userInfo;
			},
		},
		watch: {
			userInfo: {
				handler(val) {
					const { form, userInfo } = this;
					this.form.id = userInfo.id;
					this.form.openid = userInfo.openid;
					this.form.avatar = userInfo.avatar;
					this.form.nickname = userInfo.nickname;
					this.form.phone = userInfo.phone;
				},
				immediate: true,
				deep: true
			}
		},
		onLoad(options) {
			this.from = options.from || '';
			store.dispatch(ACTIONS.USER_INFO_GET_FUN);

			// #ifdef APP-PLUS
			this.appVersion = plus.runtime.version;
			// #endif

			let platform = uni.getSystemInfoSync().platform;
			let isShowIOSDelUser = platform === 'ios' && this.commonOnline ? true : false;
			this.isShowIOSDelUser = isShowIOSDelUser;
		},
		onUnload() {
			if(this.timer) {
				clearInterval(this.timer);  
				this.timer = null;  
			} 
		},
		methods: {
			copyTxtData(data) {
				data = data.toString();
				uni.setClipboardData({
					data,
					success: function () {
						uni.showToast({
							title: `已复制：${data}`,
							icon: 'none'
						});
					}
				});
			},
			
			async getCodeFun() {
				let that = this;
				if (!this.form.phone) {
					uni.showToast({
						title: '请输入您的手机号码!',
						icon: 'none'
					});
					return;
				} else {
					if (!getMobileIsFun(this.form.phone)) {
						uni.showToast({
							title: '请输入正确的手机号码!',
							icon: 'none'
						});
						return;
					}
				}

				this.countDownTimes();
				
				const { msg, code } = await getUserCodeApi({
					phone: this.form.phone,
					type: 2 // 1登录，2绑定手机
				});

				if (code !== 200) {
					return uni.showToast({
						icon: 'none',
						title: msg
					});
				}

				uni.showToast({
					title: msg,
					icon: 'none'
				});
			},

			countDownTimes() {
				this.isAllowOper = true;
				let second = this.time;
				this.msg = `${second}s`;
				this.timer = setInterval(() => {
					if (second > 1) {
						second--;
						this.msg = `${second}s`;
					} else {
						this.clearDownTimes();
					}
				}, 1000);
			},
		
			clearDownTimes() {
				this.isAllowOper = false;
				this.msg = '获取验证码';
				if (this.timer) {
					clearInterval(this.timer);
				}
			},

			uploadUserHead() {
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album'],
					crop: {
						width: 94, // 	Number	是	裁剪的宽度，单位为px，用于计算裁剪宽高比。
						height: 94 //	Number	是	裁剪的高度，单位为px，用于计算裁剪宽高比。
					},
					success: (res) => {
						const tempFiles = res.tempFiles;
						let resSize = tempFiles[0].size;
						let limitSize = 1 * 1024 * 1024;
						if (resSize > limitSize) {
							return uni.showToast({
								title: '上传图片大小不能超过1MB!',
								icon: 'none'
							});
						}

						pathToBase64(res.tempFilePaths[0])
							.then((base64) => {
								this.form.avatar = base64;
							})
							.catch((error) => {
								console.error(error)
							});
					}
				});
			},

			loginDelFun() {
				uni.showModal({
					title: '账户注销确认',
					content: '注销账户会清空账户所有数据，是否注销？',
					cancelText: '暂不注销',
					confirmText: '确定继续注销',
					async success(res) {
						if (res.confirm) {
							const { msg, code } = await getUserDestroyApi();

							if (code !== 200) {
								return uni.showToast({
									icon: 'error',
									title: msg
								});
							}

							uni.showToast({
								title: msg,
								icon: 'success',
								mask: true,
								duration: 1200
							});

							await store.commit('TOKEN_SET_FUN', null);
							await store.commit('USER_INFO_SET_FUN', {});

							setTimeout(() => {
								uni.navigateBack({});
							}, 1000);
						}
					}
				});
			},

			async loginOutFun() {
				await store.commit('TOKEN_SET_FUN', null);
				await store.commit('USER_INFO_SET_FUN', {});
				
				uni.showToast({
					icon: 'success',
					title: '已退出'
				});

				setTimeout(() => {
					uni.navigateBack({});
				}, 1000);
			},

			async setSaveFun() {
				const { form, rules } = this;

				let reg = /^(?:1[3-9]\d{9})$/;
				if ((this.form.phone && !reg.test(this.form.phone)) || !this.form.phone) {
					return uni.showToast({
						title: '请输入正确的手机号!',
						icon: 'none',
						mask: true,
						duration: 1500
					});
				}

				if (this.form.phone && this.userInfo.phone !== this.form.phone && !this.form.code) {
					return uni.showToast({
						title: '请输入验证码!',
						icon: 'none',
						mask: true,
						duration: 1500
					});
				}

				if (this.userInfo.phone !== this.form.phone && this.form.phone) {
					const { msg, code, data } = await getUpdatePhoneApi({
						...form
					});

					if (code !== 200) {
						return uni.showToast({
							icon: 'none',
							title: msg
						});
					}

					if (data.token) {
						await store.commit('TOKEN_SET_FUN', data.token);
						await store.dispatch(ACTIONS.USER_INFO_GET_FUN);
					}

					uni.showToast({
						title: msg,
						icon: 'none',
						mask: true,
						duration: 1500
					});
				}

				const { msg, code } = await getUpdateUserInfoApi({
					...form
				});

				if (code !== 200) {
					return uni.showToast({
						icon: 'none',
						title: msg
					});
				}

				uni.showToast({
					title: msg,
					icon: 'none',
					mask: true,
					duration: 1500
				});

				await setAsyncFunWait(1500);
				this.$store.dispatch('USER_INFO_GET_FUN');
			}
		}
	};
</script>

<style lang="scss" scoped>
	.setting-box {
		font-size: 30rpx;
		color: #fff;
	}

	.setting-form-view {
		width: 700rpx;
		margin: 90rpx auto 0;
		border-radius: 18rpx;
		background-color: RGBA(65, 54, 39, 0.6);
	}

	.form-item-view {
		padding: 26rpx 22rpx;
		border-bottom: 1px solid #7A6732;

		.item-view-title {
			width: 6em;
			color: #fff;
		}

		input {
			flex: 1;
			color: #fff;
			font-size: 28rpx;
		}

		button {
			width: 190rpx;
			height: 38rpx;
			line-height: unset;
			margin: 0 22rpx 0 0;
			padding: 0 0 0 44rpx;
			font-size: 26rpx;
			background: transparent;
			border-left: 4rpx solid #7A6732;

			&:after {
				margin: 0;
				padding: 0;
			}
		}

		&:last-child {
			border-bottom: none;
		}
	}

	.item-view-avatar {
		border: 2rpx solid #fff;
		border-radius: 100%;
		width: 88rpx;
		height: 88rpx;
	}

	.tip-txt {
		font-size: 22rpx;
		color: #FFDA4D;
		width: 700rpx;
		margin: 30rpx auto 0;
		.tip-txt-left{
			color: #f00;
			margin-right: 6rpx;
		}
		& > view {
			margin-bottom: 12rpx;
		}
	}

	.save-btns {
		font-size: 40rpx;
		color: #FEF7DD;
		width: 691rpx;
		height: 123rpx;
		margin: auto;
	}

	.logout-box {
		font-size: 38rpx;
		color: #FEF7DD;
		width: 691rpx;
		height: 123rpx;
		margin: 28rpx auto 66rpx;
		&.logout-box-active{
			color: #FFF;
			font-size: 38rpx;
		}
	}

	.beian-content {
		font-size: 24rpx;
		color: rgba(255, 255, 255, 0.5);
		width: 690rpx;
		margin: 38rpx auto 20rpx;
	}
</style>
